package vn.aptech.scrumgroup.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import vn.aptech.scrumgroup.R;
import vn.aptech.scrumgroup.model.AbstractBaseModel;
import vn.aptech.scrumgroup.model.MenuItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.Toast;
import demo.axitdn.event.TouchListener;
import demo.axitdn.physic.Unit;

public class MenuUtil extends AbstractBaseModel {

	public static final int ABOUT_ITEM_ID = 0;
	public static final int EXIT_ITEM_ID = 1;
	public static final int READ_BOOK_ID = 0;

	public static int WINDOW_WIDTH = 320;
	public static int WINDOW_HEIGHT = 480;
	// private Activity context;
	private MenuItem aboutItem;
	private MenuItem exitItem;
	private Activity context;
	public List<AbstractBaseModel> modelList;

	public MenuUtil(Context _context) {
		super(Color.BLACK, Color.WHITE);
		this.context = (Activity) _context;
		init();
	}

	public MenuUtil(Context _context, int backColor, int foreColor) {
		super(backColor, foreColor);
		this.context = (Activity) _context;
		init();
	}

	private void init() {
		modelList = new ArrayList<AbstractBaseModel>();
		if (WINDOW_HEIGHT > WINDOW_WIDTH) {
			aboutItem = new MenuItem(25, 478, 16, MenuItem.ABOUT, backColor,
					foreColor);
			exitItem = new MenuItem(325, 478, 16, MenuItem.EXIT, backColor,
					foreColor);
		} else {
			aboutItem = new MenuItem(25, 325 * Unit.i / Unit.j, 16,
					MenuItem.ABOUT, backColor, foreColor);
			exitItem = new MenuItem(478 * Unit.j / Unit.i, 325 * Unit.i
					/ Unit.j, 16, MenuItem.EXIT, backColor, foreColor);
		}
		aboutItem.addTouchListener(new TouchListener() {
			int x, y;

			@Override
			public boolean onReleased(int x, int y) {
				// TODO Auto-generated method stub
				if (aboutItem.getPressState()) {
					aboutItem.setPressState(false);
					float dx = x - this.x;
					float dy = y - this.y;
					float delta = (float) Math.sqrt(dx * dx + dy * dy);
					if (delta < 4) {
						context.showDialog(ABOUT_ITEM_ID);
					}
					aboutItem.isBrilliant = false;
				}
				return false;
			}

			@Override
			public boolean onPressed(int x, int y) {
				// TODO Auto-generated method stub
				if (aboutItem.isPointOf(x, y)) {
					aboutItem.setPressState(true);
					aboutItem.isBrilliant = true;
					this.x = x;
					this.y = y;
				}
				return false;
			}

			@Override
			public boolean onDragged(int x, int y) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		modelList.add(aboutItem);
		exitItem.addTouchListener(new TouchListener() {
			int x, y;

			@Override
			public boolean onReleased(int x, int y) {
				// TODO Auto-generated method stub
				exitItem.setPressState(false);
				float dx = x - this.x;
				float dy = y - this.y;
				float delta = (float) Math.sqrt(dx * dx + dy * dy);
				if (delta < 4) {
					context.showDialog(EXIT_ITEM_ID);
				}
				exitItem.isBrilliant = false;
				return false;
			}

			@Override
			public boolean onPressed(int x, int y) {
				// TODO Auto-generated method stub
				if (exitItem.isPointOf(x, y)) {
					exitItem.setPressState(true);
					exitItem.isBrilliant = true;
					this.x = x;
					this.y = y;
				}
				return false;
			}

			@Override
			public boolean onDragged(int x, int y) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		modelList.add(exitItem);
	}

	@Override
	public boolean isPointOf(float x, float y) {
		// TODO Auto-generated method stub
		for (AbstractBaseModel model : modelList) {
			if (model.isPointOf(x, y)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void changeColor(int color) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDraw(Canvas c) {
		// TODO Auto-generated method stub
		for (AbstractBaseModel model : modelList) {
			model.onDraw(c);
		}
	}

	@Override
	public void onUpdate(double t) {
		// TODO Auto-generated method stub

	}

	@Override
	public void fireTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		// super.fireTouchEvent(event);
		for (AbstractBaseModel model : modelList) {
			if (model.isPointOf(event.getX(), event.getY())) {
				model.fireTouchEvent(event);
			}
		}
	}

	public static Dialog createConfirmDialog(final Context context,
			int iconResourceId, String message, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context)
				.setIcon(iconResourceId)
				.setNegativeButton(R.string.CANCEL,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						})
				.setPositiveButton(R.string.OK,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(Intent.ACTION_MAIN);
								intent.addCategory(Intent.CATEGORY_HOME);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								context.startActivity(intent);
							}
						}).setMessage(message);
		if (title != null) {
			builder.setTitle(title);
		}
		return builder.create();
	}

	public static Dialog createAlertDialog(final Context context,
			int iconResourceId, String message, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context)
				.setIcon(iconResourceId)
				.setNegativeButton(R.string.OK,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						}).setMessage(message);
		if (title != null) {
			builder.setTitle(title);
		}
		return builder.create();
	}

	public static void createMenu(Menu menu) {
		android.view.MenuItem about = menu.add(0, READ_BOOK_ID, 0, R.string.READ_BOOK);
		// about.setAlphabeticShortcut('a');
		// about.setIcon(R.drawable.ic_launcher);
		// android.view.MenuItem exit = menu.add(0, EXIT_ITEM_ID, EXIT_ITEM_ID,
		// R.string.EXIT);
		// menu.add(0, 1, 1, "Exit");
		// menu.add(0, 0, 0, "About");
	}

	public static void menuSelected(int featureId, android.view.MenuItem item, Context context) {
		if(featureId == READ_BOOK_ID){
			try {
				// Check file is existed
				String extStorageDirectory = Environment
						.getExternalStorageDirectory().toString() + "/Scrum Book";
				File book = new File(extStorageDirectory + "/scrumguide_en.pdf");
				if (!book.exists()) {
					File extDir = new File(extStorageDirectory);
					if (!extDir.exists()) {
						if (!extDir.mkdir()) {
							Toast.makeText(context, "Cannot create Scrum Book folder",
									Toast.LENGTH_LONG).show();
							return;
						}
					}
					// copy file to sdcard
					try {
						InputStream inStream = context.getResources().openRawResource(
								R.raw.scrumguide_en);
						OutputStream outStream = new FileOutputStream(
								extStorageDirectory + "/scrumguide_en.pdf");
						byte[] buffer = new byte[1024];
						int read;
						// write file
						while ((read = inStream.read(buffer)) != -1) {
							outStream.write(buffer, 0, read);
						}
						inStream.close();
						outStream.flush();
						outStream.close();
					} catch (NotFoundException ne) {
						Toast.makeText(context,
								"Cannot open scrumguide_en.pdf in raw folder",
								Toast.LENGTH_LONG).show();
						return;
					} catch (IOException ex) {
						Toast.makeText(context, "Cannot write to sdcard",
								Toast.LENGTH_LONG).show();
						return;
					} catch (Exception ex) {
						Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG)
								.show();
						return;
					}
				}
				// ReadFile
				Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
				book = new File(extStorageDirectory + "/scrumguide_en.pdf");
				pdfIntent.setDataAndType(
						Uri.fromFile(book),
						"application/pdf");
				pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				context.startActivity(pdfIntent);
			} catch (ActivityNotFoundException ae) {
				Toast.makeText(context,
						"No Application available to view this document, please install a PDF reader app like Adobe Reader, etc.",
						Toast.LENGTH_LONG).show();
			} catch (Exception ex) {
				Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG);
			}
		}
	}
}
